import {AsyncStorage} from 'react-native'
import {AuthModel, ChatModel} from "./model";
import {kAuthorization, kContentType} from "../constant";
import Request from "../utils/Request";

const moment = require('moment');
const STORAGE_KEY = "STORAGE_KEY_chat";
export default {
    namespace: 'chat',
    state: {
        friendList: [],
        loading: false,
        messageList: null,
        socket: null,
        searchUsers: null,
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {


        // 保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        // 本地恢复
        * restoreFromStorage({payload}, {call, put, select}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },
        //清除数据
        * clear({payload}, {put}) {
        },

        //获取朋友列表
        * fetchFriends({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            if (!payload) payload = {id: auth.userInfo.id};
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            yield put({type: 'save', payload: {loading: true}});
            const friendList: friendItem[] = yield call(Request.get, Request.getApi().chatList, payload);
            if (friendList && Array.isArray(friendList)) {
                yield put({
                    type: 'save',
                    payload: {friendList, loading: false}
                })
            } else {
                yield put({type: 'save', payload: {loading: false}});
            }
        },


        //消息列表
        * fetchMessageList({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            let chat: ChatModel = yield select(state => state.chat);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            payload['sender'] = auth.userInfo.account;
            yield put({type: 'save', payload: {loading: true}});
            const result: messagePagination = yield call(Request.get, Request.getApi().messageList, payload);
            if (result) {
                if (!chat.messageList) chat.messageList = {content: []};
                const resultList = result.content.map((message: messageItem) => ({
                    ...message,
                    _id: message.id,
                    text: message.content,
                    createdAt: moment(message.date).toDate(),
                    user: {
                        _id: message.sender,
                        name: message.nickname,
                        avatar: message.avatar ? message.avatar : '',
                    }
                }));
                chat.messageList.first = result.first;
                chat.messageList.last = result.last;
                chat.messageList.number = result.number;
                chat.messageList.numberOfElements = result.numberOfElements;
                chat.messageList.size = result.size;
                chat.messageList.totalElements = result.totalElements;
                chat.messageList.totalPages = result.totalElements;
                if (payload.loadmore) {
                    const content = chat.messageList.content;
                    chat.messageList.content = content.concat(resultList);
                } else {
                    chat.messageList.content = resultList;
                }
                yield put({
                    type: 'save',
                    payload: {...chat, loading: false}
                })
            } else {
                yield put({type: 'save', payload: {messageList: null, loading: false}});
            }
        },

        *clearList({payload},{put,select}){
          const chat:ChatModel = yield select(state=>state.chat);
          chat.messageList = null;
          yield put({
              type:"save",
              payload:{...chat}
          })
        },

        //发送消息
        * sendMessage({payload}, {call, put, select}) {
            let chat: ChatModel = yield select(state => state.chat);
            let content = [];
            content = Object.assign(content, chat.messageList.content);
            content.unshift(payload.message);
            chat.messageList.content = content;
            yield put({
                type: 'save',
                payload: {...chat}
            });

            if (payload.save) {
                yield put({
                    type: 'saveMessage',
                    payload: payload.origin
                })
            }
        },


        //保存消息
        * saveMessage({payload}, {call, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            let params = {params: payload};
            params[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            params[kContentType] = 'application/json';
            yield call(Request.post, Request.getApi().saveMessage, params);
        },


        * saveSocketInstant({payload}, {put}) {
            yield put({type: 'save', payload})
        },

        //建立好友关系
        * contact({payload}, {call, select}) {
            let params = {params: {...payload}};
            const auth: AuthModel = yield select(state => state.auth);
            params[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            params[kContentType] = 'application/json';
            yield call(Request.post, Request.getApi().contact, params);
        },


        //搜索用户
        * searchUser({payload}, {call, put, select}) {
            if (!payload) payload = {};
            const auth: AuthModel = yield select(state => state.auth);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const data = yield call(Request.get, Request.getApi().searchUser,payload);
            if (data) {
                yield put({
                    type: 'save',
                    payload: {searchUsers: data}
                })
            }
        },

    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};
